package com.cola.colaboot.utils;

import com.cola.colaboot.module.system.pojo.SysAccess;

import java.util.ArrayList;
import java.util.List;

public class MenuUtil {

    public static List<SysAccess> setTreeRemoveMethod(List<SysAccess> accessList){
        accessList.removeIf(access -> access.getMenuLevel() == 0);
        return setTree(accessList);
    }

    public static List<SysAccess> setTree(List<SysAccess> accessList){
        List<SysAccess> res = new ArrayList<>();
        for (int i = 0; i < accessList.size(); i++) {
            SysAccess access = accessList.get(i);
            if (access.getParentId() == null) {//匹配一级部门
                accessList.remove(access);
                res.add(setChild(access, accessList));
            }
        }
        return res;
    }

    private static SysAccess setChild(SysAccess parent, List<SysAccess> accessList) {
        List<SysAccess> child = parent.getChildren() == null ? new ArrayList<>() : parent.getChildren();
        for (int i = 0; i < accessList.size(); i++) {
            SysAccess access = accessList.get(i);
            if (parent.getId().equals(access.getParentId())) {
                SysAccess access1 = setChild(access, accessList);
                child.add(access1);
                i--;
                accessList.remove(access);
            }
        }
        parent.setChildren(child);
        return parent;
    }
}
